from django.shortcuts import render
from django.utils import timezone

# Create your views here.permission_classes 意思是 权限，api_view 意思是 接口
from rest_framework.decorators import api_view,permission_classes
from rest_framework.response import Response
#导入相关的模型
from .models import Goods,AdminProfile,AdminLog
from .serializers import GoodsSerializer,AdminProfileSerializer,AdminLogSerializer
#认证视图模块
from rest_framework.views import APIView
from rest_framework import status 
from django.contrib.auth.models import User
from rest_framework.permissions import AllowAny,IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.exceptions import TokenError
#登录.authenticate这个库的函数的作用是验证用户名和密码，返回用户对象
from django.contrib.auth import authenticate
@api_view(['GET'])
def goods_list(request):
  """获取新鲜好物列表"""
  goods = Goods.objects.filter(is_active=True).order_by('-create_at')[:4]
  serializer = GoodsSerializer(goods,many=True,context={'request':request})
  return Response(serializer.data)
@api_view(['GET'])
def goods_detail(request, pk):
  try:
    goods = Goods.objects.get(pk=pk,is_active=True)
    serializer = GoodsSerializer(goods,context={'request':request})
    return Response(serializer.data)
  except Goods.DoesNotExist:
    return Response({'error':'商品不存在'},status=404)

#添加认证视图
class RegisterView(APIView):
  permission_classes = [AllowAny]
  def post(self,request):
    username = request.data.get('username')
    password = request.data.get('password')
    email = request.data.get('email','')
    if User.objects.filter(username=username).exists():
      return Response({
        'error':'用户已存在'
      },status=status.HTTP_400_BAD_REQUEST)
    user = User.objects.create_user(
      username=username,
      email=email,
      password=password
    )
    refresh = RefreshToken.for_user(user)
    return Response({
      'refresh': str(refresh),
      'access': str(refresh.access_token),
      'user':{
        'id': user.id,
        'username': user.username,
        'email': user.email
      }
    }, status=status.HTTP_201_CREATED)

class UserProfileView(APIView):
  permission_classes = [IsAuthenticated]
  def post(self,request):
    try:
      refresh_token = request.data.get('refresh')
      token = RefreshToken(refresh_token)
      token.blacklist()
      return Response({'message':'退出成功'},status=status.HTTP_200_OK)
    except TokenError:
      return Response({'message':'无效的token'},status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
def goods_reviews(request,pk):
   """获取商品评价（空数据返回）"""
   return Response({
    'results':[],
    'count': 0
   })
@api_view(['GET'])
def goods_recommend(request,pk):
  """获取推荐商品（获取其他商品）"""
  try:
    # 获取当前商品之外的4个商品
    recommond = Goods.objects.filter(is_active=True).exclude(pk=pk)[:4]
    serializer = GoodsSerializer(recommond,many=True,context={'request':request})
    return Response(serializer.data)
  except Exception:
    return Response([])

@api_view(['POST'])
@permission_classes([AllowAny])
def admin_login(request):
  """管理员登录接口"""
  username = request.data.get('username')
  password = request.data.get('password')
  user = authenticate(username=username,password=password)
  if not user:
    return Response({'error':'用户名和密码错误'},status=401)
  refresh = RefreshToken.for_user(user)
  return Response({
    'access': str(refresh.access_token), # 访问令牌
    'refresh': str(refresh), # 刷新令牌
    # 用户信息
    'user':{
      'id': user.id,
      'username':user.username,
      'email':user.email,
      'is_staff': user.is_staff,
      'is_superuser': user.is_superuser
    }
  })

@api_view(['GET','PUT'])
@permission_classes([IsAuthenticated])
def admin_profile_manage(request):
  """管理员个人资料管理"""
  # 获取管理员信息
  profile,created = AdminProfile.objects.get_or_create(user=request.user)
  if request.method == 'GET':
    serializer = AdminProfileSerializer(profile,context={'request':request})
    return Response(serializer.data)
  elif request.method == 'PUT':
    serializer = AdminProfileSerializer(profile,data=request.data,partial=True,context={'request':request})
    if serializer.is_valid():
      serializer.save()
      return Response(serializer.data)
    return Response(serializer.errors,status=400)

#管理员密码修改
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def admin_change_password(request):
  """管理员修改密码"""
  # 权限已通过IsAdminUser验证
  old_password = request.data.get('old_password')
  new_password = request.data.get('new_password')
  if not request.user.check_password(old_password):
    return Response({'error':'原密码错误'},status=400)
  request.user.set_password(new_password)
  request.user.save()
  return Response({'message': '密码修改成功'})
  
#管理头像上传
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def admin_upload_avatar(request):
  """管理员头像上传"""
  # 权限已通过IsAdminUser验证
  profile, created = AdminProfile.objects.get_or_create(user=request.user)
  if 'avatar' in request.FILES:
      profile.avatar = request.FILES['avatar']
      profile.save()
      serializer = AdminProfileSerializer(profile, context={'request': request})
      return Response(serializer.data)
  return Response({'error': '请上传头像文件'}, status=400)

#仪表盘数据统计
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def admin_dashboard_stats(request):
    """仪表盘统计数据"""
    # 权限已通过IsAdminUser验证
    
    total_goods = Goods.objects.count()
    active_goods = Goods.objects.filter(is_active=True).count()
    total_admins = User.objects.filter(is_staff=True).count()
    today_logs = AdminLog.objects.filter(
        create_at__date=timezone.now().date()
    ).count()
    
    return Response({
        'total_goods': total_goods,
        'active_goods': active_goods,
        'total_admins': total_admins,
        'today_logs': today_logs
    })
# 6. 管理员操作日志
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def admin_logs(request):
    """管理员操作日志"""
    logs = AdminLog.objects.filter(admin=request.user)[:20]
    serializer = AdminLogSerializer(logs, many=True)
    return Response({'results': serializer.data})

# 7. 商品管理（CRUD）
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
def admin_goods_manage(request, pk=None):
    """商品管理接口"""
    if request.method == 'GET':
        if pk:
            try:
                goods = Goods.objects.get(pk=pk)
                serializer = GoodsSerializer(goods, context={'request': request})
                return Response(serializer.data)
            except Goods.DoesNotExist:
                return Response({'error': '商品不存在'}, status=404)
        else:
            goods = Goods.objects.all().order_by('-create_at')
            serializer = GoodsSerializer(goods, many=True, context={'request': request})
            return Response({'results': serializer.data, 'count': goods.count()})
    
    elif request.method == 'POST':
        serializer = GoodsSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
    
    elif request.method == 'PUT':
        try:
            goods = Goods.objects.get(pk=pk)
            serializer = GoodsSerializer(goods, data=request.data, partial=True, context={'request': request})
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            return Response(serializer.errors, status=400)
        except Goods.DoesNotExist:
            return Response({'error': '商品不存在'}, status=404)
    
    elif request.method == 'DELETE':
        try:
            goods = Goods.objects.get(pk=pk)
            goods.delete()
            return Response({'message': '删除成功'})
        except Goods.DoesNotExist:
            return Response({'error': '商品不存在'}, status=404)
